package com.zs.hydrant.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {
    // 照片存储目录（可配置到application.yml）
    private static final String UPLOAD_DIR = "src/main/resources/static/upload/";

    @PostMapping
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 空文件校验
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("msg", "请选择文件");
                result.put("code", 400);
                return result;
            }

            // 生成唯一文件名（避免重复）
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = UUID.randomUUID() + suffix;

            // 创建存储目录
            new File(UPLOAD_DIR).mkdirs();

            // 保存文件
            file.transferTo(new File(UPLOAD_DIR + fileName));
            // 返回照片访问URL（后端地址+文件名）
            String photoUrl = "http://localhost:8081/api/upload/" + fileName;
            Map<String, String> data = new HashMap<>();
            data.put("url", photoUrl);
            
            result.put("success", true);
            result.put("msg", "上传成功");
            result.put("data", data);
            result.put("code", 200);
        } catch (IOException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", "上传失败：" + e.getMessage());
            result.put("code", 500);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("msg", "系统错误：" + e.getMessage());
            result.put("code", 500);
        }
        return result;
    }
}